using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class app_frame_changepassword : System.Web.UI.Page
{
    //string strPageSetId = "documents";
    //DataSet dseInputInfo = new DataSet();
    //DataSet dsePageInfo = new DataSet();
    //HtmlForm frmObj;
    //string strErrMessage = "";
    //string refererURL = "";
    //string dtFormat = "MM-dd-yyyy HH:mm:ss";
    //protected void Page_Error(object sender, EventArgs e)
    //{
    //    Response.Redirect("documents.aspx");
    //}
    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["mn"] != null)
        {
            if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
            {
                tblcontrols.Visible = false;
                tblbtn.Visible = false;
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                return;
            }
        }


        hdds.logMenuClick(Request.QueryString["mn"].ToString());

        loadHintQuestions();
        getpageicons(); // Added by srivatsan
    }
    private void loadHintQuestions()
    {
        if (IsPostBack) return;
        DataSet ds = new DataSet();
        HDDatabase hdd = new HDDatabase();
        try
        {
            ds = hdd.GetDataset("select * from sy_acr_mem where acr_id='" + "5937020e4add150Y" + "'");
            foreach (DataRow dr in ds.Tables[0].Rows)
                ddHintQstn.Items.Add(new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString()));
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in loadHintQuestions function. Error: " + e.Message);
        }
        finally
        {
            ds = null;
            hdd = null;
        }
    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    private bool validate()
    {
        security hdds = new security();
        string err = string.Empty;
        try
        {
            if (txtNewPassword.Text != txtConfirmPassword.Text)
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Confirmation Password doesn't match with the new Password specified.", true);
                return false;
            }
            if (txtNewPassword.Text == txtOldPassword.Text)
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Current password and New password is same.", true);
                return false;
            }
            if (!hdds.validatePasswordLength(txtNewPassword.Text, ref err)) // Added by 'Imran Gani' on 25-Nov-2013.
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + err, true);
                return false;
            }
            if (!hdds.validatePasswordReuseCycle(txtNewPassword.Text, ref err)) // Added by 'Imran Gani' on 25-Nov-2013.
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + err, true);
                return false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("changePassword: validate: Error: " + ex.Message);
        }
        return true;
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    protected void btnChangePassword_ServerClick(object sender, EventArgs e)
    {
        lbl_message.Text = "";
        if (!validate()) return;
        string userid = Session["userid"].ToString();
        string message = "";
        //lbl_message.Text = saveNewPassword(userid,txtOldPassword.Text, txtConfirmPassword.Text, ddHintQstn.SelectedValue,txtAnswer.Text, ref message) == true ? wrapItAsMessage("&nbsp;<img src='Images/tick4.gif' border='0'> Password changed successfully.",false) : wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + message,true); // Commented by 'Imran Gani' on 25-Nov-2013.
        if (saveNewPassword(userid, txtOldPassword.Text, txtConfirmPassword.Text, ddHintQstn.SelectedValue, txtAnswer.Text, ref message)) // Added by 'Imran Gani' on 25-Nov-2013.
        {
            AuditLog AL = new AuditLog();
            AL.WritePasswordSecurityLog(Session["user_afrowid"].ToString(), Session["user_afrowid"].ToString(), security.encrypt(txtConfirmPassword.Text), "changed password");
            AL = null;
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/tick4.gif' border='0'> Password changed successfully.", false);
            if (Request.QueryString["c_url"] != null)
            {
                string sContinueURl = HttpUtility.UrlDecode(Request.QueryString["c_url"].ToString());
                Session["View_Mode"] = null;
                Response.Redirect(sContinueURl);
            }
        }
        else
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + message, true);
        ddHintQstn.SelectedIndex = 0;//added by prithi on 05-Aug-2008
        txtAnswer.Text = "";//added by Prithi on 05-Aug-2008
    }
    private bool saveNewPassword(string userid,string oldPassword, string newPassword,string hintQstn, string hintAns, ref string message)
    {
        DataSet ds = new DataSet();
        HDDatabase hdd = new HDDatabase();
        ds = hdd.GetDataset("select * from sy_usr where user_id='" + userid.Replace("'", "''") + "'");
        message = "No user exists";
        if (ds.Tables == null)
            return false;
        if (ds.Tables.Count<1) return false;
        if (ds.Tables[0].Rows.Count<1) return false;
        if (security.decrypt(ds.Tables[0].Rows[0]["password"].ToString()) != oldPassword)
        {
            message = "Current Password is specified wrong.";
            return false;
        }
        if (ds.Tables[0].Rows.Count>1)
        {
            message = "Multiple users found.";
            return false;
        }
        ds.Tables[0].TableName = "p_usr";
        newPassword = security.encrypt(newPassword);

        //code commented and new code added for QC Portal changes. mail by Omprakash, done by Sampath
        string sql = "update sy_usr set password='" + newPassword + "',hint_question='" + hintQstn.Replace("'", "''") + "',hint_answer='" + hintAns.Replace("'", "''") + "' where af_row_id='" + ds.Tables["p_usr"].Rows[0]["af_row_id"].ToString() + "'";
        //string sql = "update sy_usr set password='" + newPassword + "',hint_question='" + hintQstn.Replace("'","''") + "',hint_answer='" + hintAns.Replace("'","''") + "' where af_row_id='" + ds.Tables["p_usr"].Rows[0]["af_row_id"].ToString() + "'";
        if (hdd.ExecuteCmdObj(new SqlCommand(sql)) > 0)
        {
            //ds.Tables["p_usr"].Rows[0]["password"] = security.encrypt(newPassword);
            //hdd.UsersinNGMODEL("update", ds);
            updatePasswordInModel(userid, newPassword,hintQstn,hintAns);
        }
        else
        {
            message = "Unable to apply the changes";
            return false;
        }
        hdd = null;        
        return true;
    }
    private bool updatePasswordInModel(string userid, string password,string hintQstn,string hintAns)
    {
        SqlConnection sc = null;
        try
        {
            HDDatabase hdd = new HDDatabase();
            sc = hdd.GetConnection("servercon");
            SqlCommand scom = new SqlCommand("update ngcompanyuser set password = '" + password + "',hint_question='" + hintQstn.Replace("'","''") + "',hint_answer='" + hintAns.Replace("'","''") + "' where company_id='" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "' and user_id='" + userid.Replace("'", "''") + "'");
            scom.Connection = sc;
            scom.Connection.Open();
            int records = scom.ExecuteNonQuery();
            scom.Connection.Close();
            sc = null;
            scom = null;
            hdd = null;
            return records > 0;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in updatePasswordInModel function. Error: " + e.Message);
            return false;
        }
        finally
        {
            if (sc != null)
            {
                if (sc.State != ConnectionState.Closed)
                {
                    sc.Close();
                }
                sc = null;
            }
        }
    }
    protected void btnreset_ServerClick(object sender, EventArgs e)
    {
        //Response.Redirect(Request.RawUrl);
        try
        {
            //if (p_format_masks_type.Items.Count>0)   p_format_masks_type.SelectedIndex = 0;
            
        }
        catch (Exception ee)
        {

        }
    }

    //public string ErrorMessage
    //{
    //    get
    //    {
    //        return this.strErrMessage;
    //    }
    //}
    private void getpageicons() // added by srivatsan to get page icons
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            imgliteral.Text = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            imgliteral.Text = "&nbsp;<img src =" + PageIcons.strdefaulticon.ToString() + "><img>&nbsp;";
        }
        finally
        {
            icons = null;
            HDD = null;
        }
    }
}
